// pages/combinedTables/combinedTables.js
const { signRecordApi, queryPageApi } = require("../../api/clockIn");
import store from "../../utils/store";

Page({
  data: {
    currentIndex: 0,
    weightData: [],
    titleWeight: [
      { date: '日期' },
      { value: '体重' }
    ],
    trainData: [],
    titleTrain: [
      { trainDate: '日期' },
      { content: '训练日记总结' },
      { opinion: '教练意见' }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      currentIndex: options.type - 1
    })
    this.fetchWeightHistory();
    this.fetchTrainingDiary();
  },

  /**
   * 标签切换事件
   */
  onTabChange(e) {
    // console.log('当前激活的标签索引：', e.detail.index);
    // if(e.detail)
  },
  // 从API获取体重数据
  async fetchWeightHistory() {
    try {
      const signRes = await signRecordApi({
        studentId: store.state.studentId,
        limit: 5,
        indicatorName: '体重'
      });
      // 关键：检查返回数据是否有效，并更新到 weightData
      if (signRes && signRes.data && Array.isArray(signRes.data)) {
        this.setData({
          weightData: signRes.data
        });
      } else {
        this.setData({
          weightData: []
        });
      }
    } catch (error) {
      console.error('体重数据获取失败:', error);
      // 发生错误时，也清空数据并显示空状态
      this.setData({
        weightData: []
      });
    }
  },

  // 从API获取训练日记
  async fetchTrainingDiary() {
    try {
      const queryRes = await queryPageApi({
        studentId: store.state.studentId
      })
      if (queryRes && queryRes.data.list && Array.isArray(queryRes.data.list)) {
        this.setData({
          trainData: queryRes.data.list
        });
      } else {
        this.setData({
          trainData: []
        });
      }
    } catch (error) {
      console.error('训练日记数据获取失败:', error);
      this.setData({
        trainData: []
      });
    }
  }
})